# _*_ coding:utf-8 _*_
import os
import time
import subprocess

def restart():
  python = sys.executable
  os.execl(python, python, * sys.argv)

def gen_log_name():
    tm = time.strftime('%Y%m%d_%H%M%S', time.localtime())
    return "checker"+tm+".log"

def check_v4l2_setup():
    try:
        mlog=open(gen_log_name(),'w')
        p = subprocess.Popen("v4l2-ctl",stdout=mlog,stderr=mlog)
    except:
        print("您尚未安装v4l-utils，正在自动安装。此过程中可能需要您输入密码。")
        os.system("sudo apt install v4l-utils")

def find_realsense_camera(mtype:str='RGB'):
    LOG_NAME=gen_log_name()
    mlog=open(LOG_NAME,'w')
    try:
        p = subprocess.Popen(["v4l2-ctl","--list-devices"], stdin=subprocess.PIPE, stdout=mlog, stderr=mlog)
    except:
        print("您尚未安装v4l-utils，正在自动安装。此过程中可能需要您输入密码。")
        os.system("sudo apt install v4l-utils")
        restart()
        return
    p.wait()
    lines=None
    idd=5 #RGB Camera by default
    if(mtype=='Depth'): idd=3 #Depth Camera
    with open(LOG_NAME,'r',encoding='utf-8') as file:
        lines=file.readlines()
        file.close()
        marker=-1
        for i,l in enumerate(lines):
            if l.find('RealSense')!=-1:
                marker=i
            if marker!=-1 and i==marker+idd:
                return l.strip()
    return None

if __name__ == "__main__":
    print(check_devices())
